using System;
using System.Collections.Specialized;
using System.ComponentModel;
using Microsoft.PowerShell.Host.ISE;

namespace Empanada
{
    public class ISEFileCollectionMonitor
    {
        public event ISEFileEventHandler FileModified;
        public event ISEFileEventHandler FileClosed;

        public ISEFileCollectionMonitor(ISEFileCollection files)
        {
            files.CollectionChanged += FilesCollectionChanged;
            foreach (var file in files)
            {
                file.PropertyChanged += FilePropertyChanged;
            }
        }

        void FilesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Remove && e.OldItems != null)
            {
                var handler = FileClosed;
                foreach (ISEFile file in e.OldItems)
                {
                    file.PropertyChanged -= FilePropertyChanged;
                    if (handler != null) handler(null, new ISEFileEventArgs{File = file});
                }
            }

            if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems != null)
            {
                foreach (ISEFile file in e.NewItems)
                {
                    file.PropertyChanged += FilePropertyChanged;
                }
            }
        }

        void FilePropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var file = (ISEFile) sender;
            if (!e.PropertyName.Equals("IsSaved", StringComparison.InvariantCultureIgnoreCase) || file.IsSaved) return;

            var handler = FileModified;
            if (handler != null) handler(this, new ISEFileEventArgs {File = file});
        }
    }

}